package com.hmdp.utils;

import ch.qos.logback.core.util.TimeUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;

/**
 * ClassName: LoginInterceptor
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/5/29 18:59
 * Version 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //1 获取session  -》  获取请求头中的token
////        HttpSession session = request.getSession();
//        String token = request.getHeader("authorization");
//        if (StrUtil.isEmpty(token)) {
//            response.setStatus(401);
//            return false;
//        }
//        //2 获取session中的用户信息   -》  基于token获取redis中的用户
////        Object user = session.getAttribute("user");
//        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
//
////        if(user == null){
////            //3 不存在拦截  返回401 未授权
////            response.setStatus(401);
////            return false;
////        }
//        if(userMap.isEmpty()){
//            //3 不存在拦截  返回401 未授权
//            response.setStatus(401);
//            return false;
//        }
//
//        //4 如果用户存在设置  到ThreadLocal   -》查询到的hash数据转换为UserDTO对象
//        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap,new UserDTO(),false);;
////        BeanUtils.copyProperties(user,userDTO);
//        UserHolder.saveUser(userDTO);
//
//        //5 刷新token有效期
//        stringRedisTemplate.expire(LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
//
//        //6 放行
//        return true;
        //1 判断是否需要拦截（ThreadLocal）中是否有用户
        if(UserHolder.getUser() == null){
            //没有  拦截并设置状态码
            response.setStatus(401);
            //拦截
            return false;
        }
        //有用户
        return true;
    }
}
